﻿using System;
using System.Web.Mvc;
using System.Web.Providers.Entities;
using System.Web.Security;
using AutoMapper;
using ClientApp.Models;
using CommonApp;
using CommonApp.Models;
using IBS.Bll;
using IBS.Bll.Accounts;
using IBS.Bll.Authority;
using IBS.Bll.KnowledgeBase;
using IBS.Bll.Security;
using IBS.Bll.Transfers;
using IBS.Dal;
using IBS.Model;
using IBS.ServiceContracts;
using System.Linq;

namespace ClientApp.Controllers
{
    public class AdmissionController : Controller
    {
        private readonly IAuthorityService authorityService;

        public AdmissionController()
        {
            var container = new IbsContainer();
            this.authorityService = container.AuthorityService;
        }

        [HttpGet]
        public ActionResult LogOn()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }

            ViewBag.DoNotNotifyAboutTimeout = true;
            ViewBag.FamiliarUser = true;
            return View("Entrance");
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    if (Roles.GetRolesForUser(model.UserName).All(r => !r.Equals("admin") && !r.Equals("operator")))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, false);
                        Session[InfoKey.EnsureSecurity] = true;

                        return RedirectToAction("Index", "Home");
                    }
                }
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            ViewBag.FamiliarUser = true;
            return View("LogOn", "_AdmissionLayout");
        }

        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            TempData.AddNotification("Your session has expired.", "error");

            return RedirectToAction("LogOn");
        }

        [Authorize]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            TempData.AddNotification("You have logged off. See you next time!", "success");

            return RedirectToAction("LogOn");
        }

        [HttpGet]
        public ActionResult Register()
        {
            ViewBag.FamiliarUser = false;
            return View("Entrance");
        }

        [HttpPost]
        public ActionResult Register(UserRequest request)
        {
            if (request.DateOfBirth < DateTime.Now.AddYears(-100) ||
                    request.DateOfBirth > DateTime.Now.AddYears(-16))
            {
                ModelState.AddModelError("DateOfBirth", "You must be at least 16 years old and not older than 100");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var regRequest = Mapper.Map<UserRequest, Request>(request);
                    regRequest.Patronymic = string.Empty;
                    regRequest.SubmitDate = DateTime.Now;
                    regRequest.UpdateLogin = string.Empty;
                    authorityService.SubmitRegRequest(regRequest);
                    return View("RegisterSuccess");
                }
                catch (BusinessException be)
                {
                    ModelState.AddModelError("", be.Message);
                    if (be.Message.Equals("Same user already exists"))
                        ModelState.AddModelError("", "Please, invent another login and change e-mail.");
                }
            }

            ViewBag.FamiliarUser = false;
            return View("Register", "_AdmissionLayout");
        }
    }
}
